import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

// 设置状态接口
interface SettingsState {
  theme: 'dark' | 'red'
  language: 'zh' | 'en'
}

// 从 localStorage 加载保存的设置，如果没有就使用默认值
const loadSettings = (): SettingsState => {
  if (typeof window === 'undefined') {
    return { theme: 'dark', language: 'zh' }
  }

  try {
    const saved = localStorage.getItem('app-settings')
    if (saved) {
      return JSON.parse(saved)
    }
  } catch (error) {
    console.warn('加载设置失败:', error)
  }

  return { theme: 'dark', language: 'zh' }
}

const initialState: SettingsState = loadSettings()

export const settingsSlice = createSlice({
  name: 'settings',
  initialState,
  reducers: {
    // 设置主题
    setTheme: (state, action: PayloadAction<'dark' | 'red'>) => {
      state.theme = action.payload
      // 保存到 localStorage
      localStorage.setItem('app-settings', JSON.stringify(state))
    },
    // 设置语言
    setLanguage: (state, action: PayloadAction<'zh' | 'en'>) => {
      state.language = action.payload
      // 保存到 localStorage
      localStorage.setItem('app-settings', JSON.stringify(state))
    }
  }
})

export const { setTheme, setLanguage } = settingsSlice.actions
export default settingsSlice.reducer
